package sk.vrto.web.presenters;

import com.google.common.eventbus.Subscribe;
import sk.vrto.web.base.Presenter;
import sk.vrto.web.events.ContactInsertedEvent;
import sk.vrto.web.events.NewEmailEvent;
import sk.vrto.web.events.UiEmailEvent;
import sk.vrto.web.views.EmailApplicationView;

/**
 * Presenter for the entry point view.
 */
public class EmailApplicationPresenter extends Presenter<EmailApplicationView> {

    /**
     * When contact is successfully inserted, the new contact window  is closed.
     * @param e Triggering event
     */
    @Subscribe
    public void onContactInserted(ContactInsertedEvent e) {
        view.getNewContactWindow().getParent().removeWindow(view.getNewContactWindow());
    }

    /**
     * When an email is being either forwarded or replied to, this listener method
     * ensures that the new email window is active and propagates FW/RE event.
     * @param e Triggering event
     */
    @Subscribe
    public void onForwardEmail(UiEmailEvent.FwReAddWindowEvent e) {
        assertEmailWindow();
        if (UiEmailEvent.FwReAddWindowEvent.FwRe.FORWARD == e.getFwOrRe()) {
            eventBus.post(new UiEmailEvent.FwEvent(e.getEmail()));
        } else if (UiEmailEvent.FwReAddWindowEvent.FwRe.REPLY == e.getFwOrRe()) {
            eventBus.post(new UiEmailEvent.ReEvent(e.getEmail()));
        }
    }

    /**
     * Asserts, that new email window is opened and if event carries
     * contact, then it propagates {@link NewEmailEvent}.
     * @param e Triggering event
     */
    @Subscribe
    public void onOpenWindow(UiEmailEvent.OpenWindowEvent e) {
        assertEmailWindow();
        view.getNewEmailWindow().setVisible(true);
        view.getNewEmailWindow().center();
        if (null != e.getContact()) {
            eventBus.post(new NewEmailEvent(e.getContact()));
        }
    }

    public void closeApplication() {
        //  TODO implement some user service
        view.getMainWindow().getApplication().close();
    }

    private void assertEmailWindow() {
        if (null == view.getNewEmailWindow().getParent()) {
            view.getMainWindow().addWindow(view.getNewEmailWindow());
        }
    }

}
